from django.shortcuts import render
from django.shortcuts import redirect
from django.urls import  reverse
from django.http import HttpResponse,JsonResponse
from myadmin.models import User,Shop,Category,Product

def add(request):
    cartlist = request.session.get('cartlist',{})

    pid = request.GET.get('pid',None)
    if pid is not None:
        product = Product.objects.get(id=pid).toDict()
        product['num'] = 1

        if pid in cartlist:
            cartlist[pid]['num'] += product['num']
        else:
            cartlist[pid] = product
        request.session['cartlist'] = cartlist

    return JsonResponse({'cartlist':cartlist})


def delete(request):
    cartlist = request.session.get('cartlist',{})
    del cartlist[pid]
    request.session['cartlist'] = cartlist
    return JsonResponse({'cartlist':cartlist})

def clear(request):
    request.session['cartlist'] = {}
    return JsonResponse({'cartlist': {}})

def change(request):
    cartlist = request.session.get('cartlist',{})
    pid = request.GET.get('pid',0)
    m = int(request.GET.get('num',1))
    if m < 1:
        m = 1
    cartlist[pid]['num'] = m
    request.session['cartlist'] = cartlist
    return JsonResponse({'cartlist':cartlist})

